package utils;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {
    private static final String TAG = "FileUtil";
    private static int countFile = 0;

    public static int getFileAndDirectory(File file) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File fileIndex : files) {
                    if (fileIndex.isDirectory()) {
                        getFileAndDirectory(fileIndex);
                    } else {
                        countFile++;
                    }
                }
            }
        //Log.d(TAG, "getFileAndDirectory: countFile = " + countFile);
        return countFile;
    }

    //该方法用于计算单层目录文件数量
    private static int mFileNum;
    public static int getFileNum(File file){
        if (file.isDirectory()){
            String[] strings = file.list();
            if (strings != null){
                mFileNum = strings.length;
            }
        }
        Log.d(TAG, "getFileNum: mFileNum = " + mFileNum);
        return mFileNum;
    }

    public static void saveDataToFile(byte[] bytes, float living ,int width, int height, int angle, String filePath){
        Log.d(TAG, "saveDataToFile: filePath = " + filePath);
        checkFolder(filePath);
        long currentTime = System.currentTimeMillis();
            File dataFile = new File(filePath + "/"+ "fake_" + living + "_" + width + "_" +  height + "_" + angle + "_" + currentTime + ".bitlog");
            if (!dataFile.exists()) {
                dataFile.getParentFile().mkdirs();
                try {
                    dataFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        if (bytes != null){
            Log.d(TAG, "living_test saveDataToFile: bytes.length = " + bytes.length);
        }
        saveByteToBit(bytes,dataFile);
    }


    private static void saveByteToBit(byte[] bytes, File filePath){
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(bytes);
            fos.close();
            //Log.d(TAG, "living_test saveByteToBit: 写入成功: " + filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void checkFolder(String path) {
        File folders = new File(path);
        if (!folders.exists()){
            folders.mkdirs();
        }
    }

}
